<?php

namespace App\Orchid\Screens\Category;

use App\Models\Category;
use Orchid\Screen\Screen;
use Orchid\Screen\Actions\Link;
use Orchid\Support\Facades\Toast;
use Orchid\Support\Facades\Layout;
use Orchid\Screen\TD;

class CategoryListScreen extends Screen
{
    /**
     * Fetch data to be displayed on the screen.
     *
     * @return array
     */
    public function query(): iterable
    {
        return [
            'categories' => Category::orderBy('name')->paginate(),
        ];
    }

    /**
     * The name of the screen displayed in the header.
     */
    public function name(): ?string
    {
        return '分类管理';
    }

    /**
     * Display header description.
     */
    public function description(): ?string
    {
        return '管理所有文章分类';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            Link::make('新建分类')
                ->icon('plus')
                ->route('platform.categories.create'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]
     */
    public function layout(): iterable
    {
        return [
            Layout::table('categories', [
                TD::make('name', '分类名称')
                    ->render(fn (Category $category) => $category->name),
                    
                TD::make('slug', 'Slug')
                    ->render(fn (Category $category) => $category->slug),
                    
                TD::make('description', '描述')
                    ->render(fn (Category $category) => $category->description ?? '-'),
                    
                TD::make('created_at', '创建时间')
                    ->render(fn (Category $category) => $category->created_at->format('Y-m-d H:i:s')),
            ]),
        ];
    }
    
    /**
     * Remove category
     *
     * @param Category $category
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function remove(Category $category)
    {
        // 检查是否有子分类
        if ($category->children()->count() > 0) {
            Toast::error('无法删除包含子分类的分类');
            return;
        }
        
        // 检查是否有关联的文章
        if ($category->posts()->count() > 0) {
            Toast::error('无法删除包含文章的分类');
            return;
        }
        
        $category->delete();
        
        Toast::info('分类已删除');
    }
}